import React, { useEffect } from 'react'
import { View } from 'react-native'
import { Text } from 'react-native-elements'
import * as WeChat from 'react-native-wechat';

function weixinLogin() {
    let scope = 'snsapi_userinfo';
    let state = 'wechat_sdk_abcs';

    WeChat.registerApp('wx376ae6369085284b').then(e => {
        console.log('res'+e);
        WeChat.sendAuthRequest("snsapi_userinfo").then(e => {
            console.log('send'+e);
        }).catch(e => {
            console.log(e);
        })
    })

    //判断微信是否安装
    // console.log(1);
    // WeChat.isWXAppInstalled()
    //     .then((isInstalled) => {
    //         console.log(2);
    //         if (isInstalled) {
    //             console.log(3);
    //             // 获取微信授权
    //             WeChat.sendAuthRequest(scope, state)
    //                 .then(responseCode => {
    //                     //授权成功获取token
    //                     console.log(4);
    //                     getAccessToken(responseCode);
    //                 })
    //                 .catch(error => {
    //                     console.log(5);
    //                     alert('登录授权发生错误：', error.message, [
    //                         { text: '确定' }
    //                     ]);
    //                 })
    //         } else {
    //             console.log(6);
    //             alert('没有安装微信', '请先安装微信客户端在进行登录', [
    //                 { text: '确定' }
    //             ])
    //         }
    //     })
}

function getAccessToken(responseCode) {
    let appId = '你申请的appid';
    let secret = '你申请的secret';
    switch (parseInt(responseCode.errCode)) {
        // 用户换取access_token的code，仅在ErrCode为0时有效  
        case 0:
            //获取token值
            getRequest('https://api.weixin.qq.com/sns/oauth2/access_token?appid=' + appId + '&secret=' + secret + '&code=' + responseCode.code + '&grant_type=authorization_code')
                .then(res => {
                    //授权成功，获取用户头像等信息
                    getUserInfoFormWx(res);
                })
                .catch(err => {

                })
            break;
        case -4:
            //用户拒绝
            break;
        case -2:
            //用户取消
            break;
    }
}

function getUserInfoFormWx(res) {
    getRequest('https://api.weixin.qq.com/sns/userinfo?access_token=' +
        res.access_token + '&openid=' + res.openid).then(res => {
            ToastAndroid.show('用户信息' + JSON.stringify(res),
                ToastAndroid.SHORT)
        }
        ).catch(err => { })
}

const Weixin_Login = () => {
    useEffect(() => {
        try {
            WeChat.registerApp('wx3cd709556f75813b');
            
        } catch (e) {
            console.error(e);
        }

        weixinLogin()
    })

    return (
        <View>
            <Text>
                Weixin_Login
            </Text>
        </View>
    )
}

export default Weixin_Login
